#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    :QMainWindow(parent)
    ,ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->addButton->setDisabled(true);
    ui->deleteButton->setDisabled(true);

    view = new TodoView;
    model = new TodoModel;
    p = new ItemDelegate;

    view->setItemDelegate(p);
    view->setModel(model);

    ui->horizontalLayout_3->insertWidget(0, view);

    connect(view, &QListView::clicked, this, &MainWindow::viewClicked);
}

MainWindow::~MainWindow()
{

}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (!arg1.trimmed().isEmpty()) {
        ui->addButton->setDisabled(false);
    } else {
        ui->addButton->setDisabled(true);
    }
}

void MainWindow::on_addButton_clicked()
{
    model->addRow(ui->lineEdit->text().trimmed());
    ui->lineEdit->clear();
}

void MainWindow::on_deleteButton_clicked()
{
    model->deleteRow(view->currentIndex().row());
    view->setCurrentIndex(QModelIndex());
    ui->deleteButton->setDisabled(true);
}

void MainWindow::viewClicked(const QModelIndex index)
{
    ui->deleteButton->setDisabled(false);
}

void MainWindow::on_lineEdit_returnPressed()
{
    if (!ui->lineEdit->text().trimmed().isEmpty()) {
        on_addButton_clicked();
    }
}
